package cn.lili.modules.goods.entity.dos;

import cn.hutool.core.util.StrUtil;
import cn.lili.common.enums.WhetherEnum;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SpringContextUtil;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.enums.SalesModeEnum;
import cn.lili.modules.goods.entity.enums.SupplierEnum;
import cn.lili.modules.search.entity.dos.EsGoodsIndex;
import cn.lili.modules.search.entity.dos.EsSupplierGoodsIndex;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.mybatis.model.BaseSceneEntity;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.BeanUtils;

import javax.validation.constraints.Max;
import java.io.Serial;
import java.util.Date;

/**
 * 商品sku
 *
 * @author pikachu
 * @since 2020-02-23 9:14:33
 */
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("li_goods_sku")
@ApiModel(value = "商品sku对象")
@NoArgsConstructor
@Slf4j
public class GoodsSku extends BaseSceneEntity{

    public static final String ID = "id";
    public static final String SN_KEY = "sn";
    public static final String PRICE_KEY = "price";
    public static final String VIP_PRICE_KEY = "vipPrice";
    public static final String COST_KEY = "cost";
    public static final String WEIGHT_KEY = "weight";
    public static final String QUANTITY_KEY = "quantity";

    //绿色积分
    public static final String GREEN_SCORE = "greenscore";

    public static final String IMAGES_KEY = "images";
    public static final String IS_FREE_KEY = "isFree";

    @Serial
    private static final long serialVersionUID = 4865908658161118934L;

    @ApiModelProperty(value = "商品id")
    private String goodsId;

    @ApiModelProperty(value = "规格信息json", hidden = true)
    private String specs;

    @ApiModelProperty(value = "规格信息")
    private String simpleSpecs;

    @ApiModelProperty(value = "配送模版id")
    private String freightTemplateId;

    @ApiModelProperty(value = "是否是促销商品")
    private Boolean promotionFlag;

    @ApiModelProperty(value = "促销价")
    private Double promotionPrice;

    @ApiModelProperty(value = "商品名称")
    private String goodsName;

    @Length(max = 30, message = "商品规格编号太长，不能超过30个字符")
    @ApiModelProperty(value = "商品编号")
    private String sn;

    @ApiModelProperty(value = "品牌id")
    private String brandId;

    @ApiModelProperty(value = "分类path")
    private String categoryPath;

    @ApiModelProperty(value = "子分类路径，多个按-分割")
    private String categoryPathSon;

    @ApiModelProperty(value = "子分类名称，多个按-分割")
    private String categoryPathSonName;

    @ApiModelProperty(value = "计量单位")
    private String goodsUnit;

    @ApiModelProperty(value = "卖点")
    private String sellingPoint;

    @ApiModelProperty(value = "重量")
    @Max(value = 99999999, message = "重量不能超过99999999")
    private Double weight;
    /**
     * @see GoodsMarketEnum
     */
    @ApiModelProperty(value = "上架状态")
    private String marketEnable;

    @ApiModelProperty(value = "商品详情")
    private String intro;

    @Max(value = 99999999, message = "价格不能超过99999999")
    @ApiModelProperty(value = "商品价格")
    private Double price;

    @Max(value = 99999999, message = "价格不能超过99999999")
    @ApiModelProperty(value = "建议零售价")
    private Double retailPrice;

    @Max(value = 99999999, message = "价格不能超过99999999")
    @ApiModelProperty(value = "商品价格")
    private Double vipPrice;

    @Max(value = 99999999, message = "价格不能超过99999999")
    @ApiModelProperty(value = "飞语会员价")
    private Double fyVipPrice;

    @Max(value = 99999999, message = "成本价格99999999")
    @ApiModelProperty(value = "成本价格")
    private Double cost;

    @ApiModelProperty(value = "浏览数量")
    private Integer viewCount;

    @ApiModelProperty(value = "购买数量")
    private Integer buyCount;

    @Max(value = 99999999, message = "库存不能超过99999999")
    @ApiModelProperty(value = "库存")
    private Integer quantity;

    @ApiModelProperty(value = "商品好评率")
    private Double grade;

    @ApiModelProperty(value = "缩略图路径")
    private String thumbnail;

    @ApiModelProperty(value = "大图路径")
    private String big;

    @ApiModelProperty(value = "小图路径")
    private String small;

    @ApiModelProperty(value = "原图路径")
    private String original;

    @ApiModelProperty(value = "店铺分类id")
    private String storeCategoryPath;

    @ApiModelProperty(value = "评论数量")
    private Integer commentNum;

    @ApiModelProperty(value = "卖家id")
    private String storeId;

    @ApiModelProperty(value = "卖家名字")
    private String storeName;

    @ApiModelProperty(value = "运费模板id")
    private String templateId;

    /**
     * @see GoodsAuthEnum
     */
    @ApiModelProperty(value = "审核状态")
    private String authFlag;

    @ApiModelProperty(value = "审核信息")
    private String authMessage;

    @ApiModelProperty(value = "下架原因")
    private String underMessage;

    @ApiModelProperty(value = "是否自营")
    private Boolean selfOperated;

    @ApiModelProperty(value = "商品移动端详情")
    private String mobileIntro;

    @ApiModelProperty(value = "商品视频")
    private String goodsVideo;

    @ApiModelProperty(value = "是否为推荐商品", required = true)
    private Boolean recommend;

    /**
     * @see SalesModeEnum
     */
    @ApiModelProperty(value = "销售模式", required = true)
    private String salesModel;
    /**
     * @see cn.lili.modules.goods.entity.enums.GoodsTypeEnum
     */
    @ApiModelProperty(value = "商品类型", required = true)
    private String goodsType;


    @ApiModelProperty(value = "供应商ID")
    private String supplierId;
    @ApiModelProperty(value = "供应商名称")
    private String supplierName;

    @ApiModelProperty(value = "供应商商品ID")
    private String supplierGoodsId;
    @ApiModelProperty(value = "供应商SKU ID")
    private String supplierSkuId;

    /**
     * @see WhetherEnum
     */
    @ApiModelProperty(value = "支持代发")
    private Boolean supportProxy;

    @ApiModelProperty(value = "支持采购")
    private Boolean supportPurchase;


    /**
     * @see SupplierEnum
     */
    @ApiModelProperty(value = "供应商类型")
    private String supplierEnum;

    @ApiModelProperty(value = "是否是代理商品")
    private Boolean isProxyGoods = false;

    @ApiModelProperty(value = "是否绿色商品")
    private Boolean isGreenGoods = false;

    @ApiModelProperty(value = "绿色积分")
    private Double greenScore;

    @ApiModelProperty(value = "最大F分抵扣值")
    private Double maxfNumber;

    @ApiModelProperty(value = "商品价值（盲盒商品专用）")
    private String goodsValue;

    @ApiModelProperty(value = "返佣绿色积分")
    @TableField(exist = false)
    private Double backGreenPoint;

    @ApiModelProperty(value = "第三方供应链平台id")
    private String thirdPartyPlatformId;

    @ApiModelProperty(value = "第三方供应链类型（1壹邦玖，2企叮咚,4海关）")
    private Integer thirdPartyPlatformType;

    @ApiModelProperty(value = "是否公益商品")
    private Boolean isCommonwealGoods = false;

    @ApiModelProperty(value = "是否上架")
    @TableField(exist = false)
    private Integer is_display;

    /**
     * 是否会员商品
     */
    @TableField(updateStrategy = FieldStrategy.IGNORED)
    private Boolean isVipGoods;

    @ApiModelProperty(value = "是否绿色积分卷抵扣")
    private Boolean isGreenSecurities;

    @ApiModelProperty(value = "最大绿色积分卷抵扣金额")
    private Double isGreenSecuritiesPrice;

    @ApiModelProperty(value = "是否全返商品")
    private Boolean isResultGoods;

    /**
     * 盲盒规则ID
     */
    public String mhId;

    @ApiModelProperty(value = "是否演唱会门票")
    private Boolean isTicket;

    @ApiModelProperty(value = "是否套餐商品")
    private Boolean isMeal;

    @ApiModelProperty(value = "套餐商品价格")
    private Double mealPrice;

    @ApiModelProperty(value = "是否默认套餐商品规格")
    private Boolean isDefaultMeal;

    @ApiModelProperty(value = "套餐商品渠道")
    @TableField(exist = false)
    private Integer mealGoodsSource;

    @ApiModelProperty(value = "虚拟购买数量")
    private Integer virtualBuyCount;

    @ApiModelProperty(value = "虚拟评价数量")
    private Integer virtualEvaluateCount;

    @ApiModelProperty(value = "是否是分销商品")
    private Boolean isDistributionGoods = false;
    /**
     * 海关编码
     */
    private String productCode;
    /**
     * 是否免税商品
     */
    private Boolean isFree;

    @ApiModelProperty("是否是一级分销")
    private Boolean isLevelDistribution;

    @ApiModelProperty("礼包id")
    private String packId;

    @ApiModelProperty("是否是礼包商品")
    @TableField(exist = false)
    private Boolean isPackGoods = false;

    @ApiModelProperty("绿色积分分佣值-计算后的值")
    private Double greenScoreView;

    public Double getBackGreenPoint() {
        if(greenScore == null)
            return 0D;
        return generateBackGreenPoint(greenScore);
    }

//    public Double getWeight() {
//        if (weight == null) {
//            return 0d;
//        }
//        return weight;
//    }

    @Override
    public Date getCreateTime() {
        if (super.getCreateTime() == null) {
            return new Date(1593571928);
        } else {
            return super.getCreateTime();
        }
    }

    /**
     * 设置规格商品的基本商品信息
     */
    public GoodsSku(Double cost) {
        this.cost = cost;
    }
    public GoodsSku(Goods goods) {
        BeanUtils.copyProperties(goods, this);
        //商品基本信息
        this.goodsId = goods.getId();
        this.goodsName = goods.getGoodsName();
        this.goodsType = goods.getGoodsType();

        this.selfOperated = goods.getSelfOperated();
        this.sellingPoint = goods.getSellingPoint();
        this.categoryPath = goods.getCategoryPath();
        this.categoryPathSon = goods.getCategoryPathSon();
        this.categoryPathSonName = goods.getCategoryPathSonName();
        this.brandId = goods.getBrandId();
        this.marketEnable = goods.getMarketEnable();
        this.intro = goods.getIntro();
        this.mobileIntro = goods.getMobileIntro();
        this.goodsUnit = goods.getGoodsUnit();
        this.grade = 100D;
        this.goodsVideo = goods.getGoodsVideo();
        //商品状态
        this.authFlag = goods.getAuthFlag();
        this.salesModel = goods.getSalesModel();
        //卖家信息
        this.storeId = goods.getStoreId();
        this.storeName = goods.getStoreName();
        this.storeCategoryPath = goods.getStoreCategoryPath();
        this.freightTemplateId = goods.getTemplateId();
        this.recommend = goods.getRecommend();
        this.goodsValue = goods.getGoodsValue();
        this.isResultGoods = goods.getIsResultGoods();
        this.isTicket = goods.getIsTicket();
        this.isMeal = goods.getIsMeal();
        //是否是礼包商品
        this.isPackGoods = StrUtil.isNotEmpty(goods.getPackId());
        //是否是一级分销
        this.setIsLevelDistribution(goods.getIsLevelDistribution() != null && goods.getIsLevelDistribution());
    }

    /**
     * 计算绿色积分返佣金额
     * @return
     */
    public Double generateBackGreenPoint(Double greenScore){
        if(greenScore == null){
            return 0.0;
        }
        SettingClient settingClient = SpringContextUtil.getBean(SettingClient.class);
        JSONObject jsonObject = null;

        if(this.isGreenGoods) {
            Setting setting = settingClient.get(SettingEnum.GREEN_GOODS.name());
            log.info("SettingEnum.GREEN_GOODS.name()-------{}",setting);
            jsonObject = JSONObject.parseObject(setting.getSettingValue());
        }else {
            Setting setting = settingClient.get(SettingEnum.NOT_GREEN_GOODS.name());
            log.info("SettingEnum.NOT_GREEN_GOODS.name()-------{}",setting);
            jsonObject = JSONObject.parseObject(setting.getSettingValue());
        }

        Integer score = jsonObject.getInteger("userProportion");
        this.backGreenPoint = CurrencyUtil.div(CurrencyUtil.mul(greenScore, score == null ? 0 : score), 100);
        return this.backGreenPoint;
    }

    public Class<? extends EsGoodsIndex> getEsIndexClass() {
        return SceneEnums.SUPPLIER.name().equals(this.getScene()) ? EsSupplierGoodsIndex.class : EsGoodsIndex.class;
    }


    @Override
    public GoodsSku clone() throws CloneNotSupportedException {
        return (GoodsSku) super.clone();
    }
}